package com.dingtalk.yuanhua_spring_project.service.impl;

import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.dingtalkyida_1_0.Client;
import com.aliyun.dingtalkyida_1_0.models.GetOpenUrlHeaders;
import com.aliyun.dingtalkyida_1_0.models.GetOpenUrlRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.dingtalk.yuanhua_spring_project.service.DingTalkYiDa1_0FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class DingTalkYiDa1_0impl implements DingTalkYiDa1_0FileService {
    private static final Logger logger = LoggerFactory.getLogger(DingTalkYiDa1_0impl.class);

    private static Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new Client(config);
    }

    public String getDownloadUrl(String accessToken, String fileUrl, String systemToken, String UserId, String appType, String fileName) throws Exception {
        Client client = createClient();
        String savePath = "";
        GetOpenUrlHeaders getOpenUrlHeaders = new GetOpenUrlHeaders();
        getOpenUrlHeaders.xAcsDingtalkAccessToken = accessToken;
        GetOpenUrlRequest getOpenUrlRequest = new GetOpenUrlRequest()
                .setSystemToken(systemToken)
                .setFileUrl(fileUrl)
                .setUserId(UserId);
        try {
            String downloadUrl = client.getOpenUrlWithOptions(appType, getOpenUrlRequest, getOpenUrlHeaders, new RuntimeOptions()).getBody().getResult();
            System.out.println(downloadUrl);
            savePath = downloadFile(downloadUrl,fileName);
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("getDownloadUrl Error code: {}, Error message: {}", err.code, err.message, err);
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("getDownloadUrl Error code: {}, Error message: {}", err.code, err.message, err);
            }
        }
        return savePath;
    }

    public static String downloadFile(String downloadUrl, String fileName) throws Exception {
        // 获取项目根目录路径
        String projectRoot = System.getProperty("user.dir");
        // 构建 file 文件夹路径
        String saveDirectory = projectRoot + "/file/";
        String savePath = saveDirectory + fileName;

        // 确保目录存在，不存在则创建
        java.io.File directory = new java.io.File(saveDirectory);
        if (!directory.exists()) {
            directory.mkdirs();  // 多级目录创建
        }

        URL url = new URL(downloadUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // 检查HTTP响应码是否为200（OK）
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 打开输入流
            try (InputStream inputStream = httpConn.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(savePath)) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        } else {
            logger.error("downloadFile: Server replied HTTP code: {}", responseCode);
        }

        httpConn.disconnect();
        return savePath;
    }




}